import json

from django.forms import model_to_dict
from django.http import JsonResponse
from django.shortcuts import render
import datetime


# Create your views here.
from common.errorcode import Error
from user.models import User
from social.models import Swiped, Friend, Vip, VipPermRelation, Permission
from django_redis import get_redis_connection

def recommend(request):
    # 1,获取
    profile = request.user.profile

    # 3.处理
    min_birth = datetime.date.today().year - profile.max_dating_age
    max_birth = datetime.date.today().year - profile.min_dating_age

    user = User.objects.filter(
        birth_year__gte=min_birth,
        birth_year__lte=max_birth,
        location=profile.location,
        sex=profile.dating_sex
    ).exclude(id=request.user.id)

    # 去除滑动过的记录
    swipeds = Swiped.objects.filter(uid=request.user.id)
    sid_list = [s.sid for s in swipeds]

    user = user.exclude(id__in=sid_list)


    # 随机的展示20条数据
    user = user.order_by("?")[:20]

    # querySet([<user1>,<user2>])
    data = [model_to_dict(u) for u in user]

    # 4.返回响应
    return JsonResponse({'code':0, 'data': data})


def like(request):
    data = json.loads(request.body)

    Swiped.add_swiped(request.user.id, data.get('sid'), 'like')

    # 设置 用户id为 sid  的用户, 得分是加 5分
    redis_cli = get_redis_connection('rank')
    redis_cli.zincrby('rank', 5, data.get('sid'))

    return JsonResponse({'code':0, 'data':'滑动成功'})


def dislike(request):
    data = json.loads(request.body)

    Swiped.add_swiped(request.user.id, data.get('sid'), 'dislike')

    # 设置 用户id为 sid  的用户, 得分是减 5分
    redis_cli = get_redis_connection('rank')
    redis_cli.zincrby('rank', -5, data.get('sid'))

    return JsonResponse({'code': 0, 'data': '滑动成功'})



def check_perm(perms):
    def outer(func):
        def inner(request):

            # 1.通过登录的用户id获取会员等级,通过会员等级,获取会员等级对应的权限
            user = User.objects.get(id=request.user.id)
            perm = VipPermRelation.objects.filter(vip_id=user.vip_id)
            # perm_list 的值 就是 用户等级对应的 所有权限的id
            perm_list = [p.perm_id for p in perm]

            # 通过权限的标识拿到 对应的id
            per = Permission.objects.get(name=perms)
            if per.id in perm_list:
                return func(request)
            else:
                return JsonResponse({'code':Error.NO_PERM, 'data': '没有权限'})
        return inner
    return outer



@check_perm('superlike')
def superlike(request):
    data = json.loads(request.body)

    Swiped.add_swiped(request.user.id, data.get('sid'), 'superlike')

    # 设置 用户id为 sid  的用户, 得分是减 5分
    redis_cli = get_redis_connection('rank')
    redis_cli.zincrby('rank', 7, data.get('sid'))

    return JsonResponse({'code': 0, 'data': '滑动成功'})




@check_perm('rewind')
def rewind(request):


    # 通过redis设置返回次数,如果次数达到3次.就不再执行下面代码
    redis_cli = get_redis_connection()

    # 1,先获取 返回的 redis
    num = redis_cli.get(f"rewind-{request.user.id}")

    # 2,判断num有没有值,如果有值,在num的基础上加1,知道num=3
    # 如果没有值,表示还没有返回,就把num的值设置为1
    if not num:
        num = 1
        now_time = datetime.datetime.now()
        expire_time = 24 * 3600 - now_time.hour * 3600 - now_time.minute * 60 - now_time.second
        redis_cli.set(f"rewind-{request.user.id}", num, expire_time)
    else:
        if int(num) >= 3:
            return JsonResponse({'code':0, 'data': '返回次数到达3次'})
        else:
            redis_cli.incr(f"rewind-{request.user.id}")

    # 获取当前用户最后一次滑动记录
    data = Swiped.objects.filter(uid=request.user.id).last()

    # 获取uid和sid,判断这两个id是否存在于交友表中
    # 如果存在就删除
    uid1 = min([data.uid, data.sid])
    uid2 = max([data.uid, data.sid])

    Friend.objects.filter(uid1=uid1, uid2=uid2).delete()

    # 删除滑动记录
    data.delete()

    return JsonResponse({'code':0, 'data': '返回成功'})


def rank(request):

    # 1.从redis中获取 分数由大到小的 前10位用户
    redis_cli = get_redis_connection('rank')
    rank = redis_cli.zrevrange('rank', 0, 9, withscores=True)

    # [(b'32', 88.0), (b'14', 66.0), (b'6', 50.0), (b'100', 34.0), (b'42', 30.0), (b'72', 20.0), (b'70', 19.0), (b'55', 11.0), (b'56', 5.0), (b'10', -10.0)]
    data = [(int(r[0]), int(r[1])) for r in rank]
    # [(32, 88), (14, 66), (6, 50), (100, 34), (42, 30), (72, 20), (70, 19), (55, 11), (56, 5), (10, -10)]

    id_list =  [int(r[0]) for r in rank]

    # id_list = [32, 14, 6, 100, 42, 72, 70, 55, 56, 10]
    user = User.objects.filter(id__in=id_list)

    # print(id_list)
    # print(user)

    user = sorted(user, key=lambda x: id_list.index(x.id))

    res = []
    for u, d in zip(user, data):
        dic = model_to_dict(u)
        dic['score'] = d[1]
        res.append(dic)

    return JsonResponse({'code':0, 'data':res})